//
//  YMTypeEffectLabel.m
//  SearchPeople
//
//  Created by YoloMao on 16/5/11.
//
//

#import "YMTypeEffectLabel.h"

@interface YMTypeEffectLabel ()

@property (nonatomic, strong) NSString *totalText;
@property (nonatomic) NSUInteger currentIndex;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation YMTypeEffectLabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.typewriteTimeInterval = 0.3;
        self.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

-(void)startType
{
    self.totalText = self.text;
    self.currentIndex = 0;
    self.text = @"";
    if (self.timer)
    {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.typewriteTimeInterval target:self selector:@selector(typeWord:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)typeWord:(id)atimer
{
    if (self.text.length == self.totalText.length)
    {
        [atimer invalidate];
        atimer = nil;
        self.typewriteEffectBlock();
    }else
    {
        self.currentIndex++;
        NSRange range = NSMakeRange(0, self.currentIndex);
        self.text = [self.totalText substringWithRange:range];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self sizeToFit];
        });
    }
}


@end
